# !/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys, json, urllib, time, requests
import numpy as np
import matplotlib.pyplot as plt
from db import get_conn
from skimage import io
from util import prefix, get_img


def label_img(id, context, url):
    plt.ion()
    image = io.imread(url)
    io.imshow(image)

    print context
    label = raw_input('label:')

    if label == '1':
        io.imsave('./img/' + id + url[-4:], image)
        save_label(id, context, url)
    elif label == '-1':
        sys.exit(0)


def label_imgs(id, img_id, context, img_url):
    if img_url[-4:] != '.jpg':
        return

    try:
        image = io.imread(img_url)
        io.imshow(image)
    except Exception, e:
        print e.message
        return

    print img_id, img_url
    print context
    label = raw_input('label:')
    # label = '1'

    if label == '-1':
        sys.exit(0)
    elif label == '1':
        io.imsave('./img/' + img_id + img_url[-4:], image)
        save_label(img_id, context, img_url)
    elif len(label) > 1:
        context_edit = label
        io.imsave('./img/' + img_id + img_url[-4:], image)
        save_label(img_id, context_edit, img_url)
    else:
        return


def save_label(id, context, url):
    conn = get_conn()
    cursor = conn.cursor()

    sql = 'INSERT INTO label_image(img_id, context, img_url)' \
          ' VALUES (%s, %s, %s)'
    param = (id, context, url)

    try:
        cursor.execute(sql, param)
    except Exception, e:
        print e

    conn.commit()
    cursor.close()
    conn.close()


if __name__ == '__main__':
    plt.ion()
    if len(sys.argv) == 1:
        start_id = 1
    else:
        start_id = sys.argv[1]

    data = get_img(start_id)

    for item in data:
        id = str(item[0])
        img_id = item[1]
        context = item[2]
        img_url = item[3]

        print 'Label index : ' + id

        label_imgs(id, img_id, context, img_url)
